package com.controller.sys;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.Result;
import com.common.log.OperationLog;
import com.common.log.OperationType;
import com.entity.sys.Notice;
import com.entity.sys.NoticeHaveRole;
import com.entity.sys.Role;
import com.service.sys.NoticeHaveRoleService;
import com.service.sys.NoticeService;
import com.service.sys.UserService;
import com.vo.sys.NoticeVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author clay
 * @since 2022-03-08
 */
@RestController
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    private NoticeService noticeService;

    @Resource
    private NoticeHaveRoleService noticeHaveRoleService;

    @Resource
    private UserService userService;

    @ApiOperation("通过id获取权限")
    @GetMapping("info/{id}")
    public Result info(@PathVariable String id) {
        return Result.success(noticeService.getById(id));
    }

    @ApiOperation("添加通知公告")
    @PostMapping("/add")
    @OperationLog(operationType = OperationType.INSERT, describe = "添加权限信息", entity = Notice.class, primaryKey = "id")
    public Result add(@RequestBody Notice notice) {
        if (noticeService.save(notice)) {
            return Result.success("操作成功");
        }
        return Result.fail("添加失败!");
    }

    @ApiOperation("修改公告")
    @OperationLog(operationType = OperationType.INSERT, describe = "修改权限信息", entity = Notice.class, primaryKey = "id")
    @PostMapping("/update")
    public Result update(@RequestBody Notice notice) {
        if (noticeService.updateById(notice)) {
            return Result.success("操作成功");
        }
        return Result.fail("修改失败!");
    }

    @ApiOperation("删除通知")
    @OperationLog(operationType = OperationType.INSERT, describe = "删除权限信息", entity = Role.class, primaryKey = "id")
    @GetMapping("/delete/{id}")
    @Transactional(rollbackFor = RuntimeException.class)
    public Result delete(@PathVariable String id) {
        if (noticeService.removeById(id)) {
            noticeHaveRoleService.remove(new QueryWrapper<NoticeHaveRole>().eq(
                    "notice_id", id
            ));
            return Result.success("操作成功");
        }
        return Result.fail("删除失败!");
    }

    @ApiOperation("获取所有通知")
    @PostMapping("/select")
    public Result all(@RequestBody Notice notice) {
        List<Notice> noticeList = noticeService.list(new QueryWrapper<Notice>().eq(
                Objects.nonNull(notice.getStatu()), "statu", notice.getStatu()
        ).like(
                !StringUtils.isEmpty(notice.getTitle()), "title", notice.getTitle()
        ).orderByDesc("create_time"));
        return Result.success(noticeList);
    }

    @ApiOperation("通知分配权限")
    @PostMapping("/noticeAssignRole/{noticeId}")
    @Transactional(rollbackFor = RuntimeException.class)
    public Result assignRole(@PathVariable String noticeId, @RequestBody List<NoticeHaveRole> noticeHaveRoles) {
        try {
            noticeHaveRoleService.remove(new QueryWrapper<NoticeHaveRole>().eq(
                    "notice_id", noticeId
            ));
            noticeHaveRoleService.saveBatch(noticeHaveRoles);
            return Result.success();
        } catch (RuntimeException e) {
            return Result.fail("分配权限失败!");
        }
    }

    @ApiOperation("根据权限获取通知")
    @PostMapping("/getNoticeByRole")
    public Result getNoticeByRole(@RequestBody List<Role> roles) {

            List<NoticeHaveRole> noticeHaveRoles = new ArrayList<>();
            for (Role role : roles) {
                noticeHaveRoles.addAll(noticeHaveRoleService.list(new QueryWrapper<NoticeHaveRole>().eq(
                        "role_id", role.getId()
                )));
            }
            System.out.println("拥有的权限：" + JSON.toJSON(roles));
            List<NoticeVo> noticeVos = new ArrayList<>();
            for (NoticeHaveRole noticeHaveRole : noticeHaveRoles) {
                Notice notice = noticeService.getById(noticeHaveRole.getNoticeId());
                if ("0".equals(notice.getStatu())) {
                    continue;
                }
                NoticeVo noticeVo = new NoticeVo();
                noticeVo.setNotice(notice);
                noticeVo.setCreateByUser(userService.getUserByUsername(notice.getCreateBy()));
                noticeVos.add(noticeVo);
            }
            return Result.success(noticeVos);

    }
}
